package cn.zymall.seckill.service.impl;

import cn.zymall.common.model.SeckillSku;
import cn.zymall.common.model.SeckillSpu;
import cn.zymall.common.model.Spu;
import cn.zymall.common.utils.redis.RedisFieldItem;
import cn.zymall.common.utils.redis.RedisUtil;
import cn.zymall.common.utils.response.HttpResult;
import cn.zymall.seckill.service.SecKillService;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author xuxianda
 * @Description: xuxianda
 * @date 2020/8/24 9:35
 * @Copyright
 * @return
 **/
@Service
public class SecKillServiceImpl implements SecKillService {

    @Autowired
    RedisUtil redisUtil;

    Gson gson = new Gson();

    /**
     * 获取抢购商品信息
     *
     * @return
     */
    @Override
    public HttpResult<SeckillSpu> getSecKillSpu(String secKillSpuId) {
        try {
            RedisFieldItem redisFieldItem = new RedisFieldItem();
            redisFieldItem.setSecKillSpuKey(secKillSpuId);
            Gson gson = new Gson();
            return new HttpResult<SeckillSpu>().success("获取成功", gson.fromJson((String) redisUtil.get(redisFieldItem.getSecKillSpuKey()), SeckillSpu.class));
        } catch (Exception e) {
            e.printStackTrace();
            return new HttpResult().fail("获取失败");
        }
    }

    /**
     * 将抢购商品写入缓存    ---测试使用
     *
     * @param spu
     * @return
     */
    @Override
    public HttpResult<SeckillSpu> addSecKillSpu(SeckillSpu spu) {
        try {
            RedisFieldItem redisFieldItem = new RedisFieldItem();
            redisFieldItem.setSecKillSpuKey(spu.getSpuId().toString());
            redisFieldItem.setSecKillSpuValue(gson.toJson(spu));
            System.out.println(redisFieldItem);
            redisUtil.set(redisFieldItem.getSecKillSpuKey(), redisFieldItem.getSecKillSpuValue());
            return new HttpResult().success("添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new HttpResult().fail("添加失败");
        }
    }

    /**
     * 将抢购商品规格写入缓存    ---测试使用
     *
     * @param sku
     * @return
     */
    @Override
    public HttpResult<SeckillSpu> addSecKillSku(SeckillSku sku) {
        try {
            RedisFieldItem redisFieldItem = new RedisFieldItem();
            redisFieldItem.setSecKillSpuKey(sku.getSpuId().toString());
            redisFieldItem.setSecKillSkuKey(sku.getSkuId().toString());
            System.out.println(redisFieldItem);
            redisUtil.set(redisFieldItem.getSecKillSkuKey() + ".sum", sku.getSum());
            return new HttpResult().success("添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new HttpResult().fail("添加失败");
        }
    }
}
